import { Controller, Get, Post, Body, Patch, Param, Delete, UseInterceptors, UploadedFile, Res } from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';
import { zip } from 'compressing';
import { join } from 'path';

@Controller('upload')
export class UploadController {
    constructor(private readonly uploadService: UploadService) { }
    
    @Post()
    @UseInterceptors(FileInterceptor('file')) // 'file'为前端表单字段名称
    async uploadFile(@UploadedFile() file) {
        console.log('file', file);
        console.log(`${file.originalname} uploaded successfully.`);
        return `Successfully uploaded ${file.originalname}`;
    }
    
    @Get('export')
    downLoad(@Res() res: Response) {
        const url = join(__dirname, '../images/1705545207094.jpg');
        res.download(url);
    }
    
    @Get('stream')
    async down(@Res() res:Response) {
        const url = join(__dirname, '../images/1705545207094.jpg');
        const tarStream = new zip.Stream();
        await tarStream.addEntry(url);
        
        res.setHeader('Content-type', 'application/octet-stream');
        
        res.setHeader(
            'Content-Disposition',
            'attachment; filename=test'
        );
        
        tarStream.pipe(res);
    }
}
